from flask import Flask
import os,time
from flask import request
import paho.mqtt.client as mqtt
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
app = Flask(__name__)
def on_message_come(lient, userdata, msg):
    print(msg.topic + " " + ":" + str(msg.payload))

@app.route("/")
def hello():
    return "Hello World!"
 
@app.route('/pic', methods = ['POST'])
def getPic():
    img = request.files['file']
    basedir = os.path.abspath(os.path.dirname(__file__))
    file_path = os.path.join(basedir, img.filename)
    img.save(file_path)
    # json_data = request.get_json()
    # image = json_data['image']
    # with open('test.jpg','wb') as f:
    #     f.write(base64.b64decode(image))
    # return True
    mail_host = 'smtp.126.com'  
    #163用户名
    mail_user = "sunduo88772922@126.com"
    #密码(部分邮箱为授权码) 
    mail_pass = "KNJNHCRERARMJRXF"
    #邮件发送方邮箱地址
    sender = mail_user
    #邮件接受方邮箱地址，注意需要[]包裹，这意味着你可以写多个邮件地址群发
    receivers = ["kidari@qq.com"]
    #设置email信息
    #邮件内容设置
    message = MIMEMultipart('related')
    #邮件主题       
    message['Subject'] = Header('dakapic '+time.strftime('%H:%M:%S', time.localtime()), 'utf-8')
    #发送方信息
    message['From'] = sender 
    #接受方信息     
    message['To'] = receivers[0]

    msgAlternative = MIMEMultipart('alternative')
    message.attach(msgAlternative)
    
    mail_msg = """
    <p>pic：</p>
    <p><img src="cid:image1"></p>
    """
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    
    # 指定图片为当前目录
    fp = open(file_path, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    
    # 定义图片 ID，在 HTML 文本中引用
    msgImage.add_header('Content-ID', '<image1>')
    message.attach(msgImage)
    #登录并发送邮件
    try:
        smtpObj = smtplib.SMTP() 
        # 连接到服务器
        smtpObj.connect(mail_host,25)
        #######替换为########
        # smtpObj = smtplib.SMTP_SSL(mail_host)
        #登录到服务器
        smtpObj.login(mail_user,mail_pass) 
        #发送
        smtpObj.sendmail(
            sender,receivers,message.as_string()) 
        #退出
        smtpObj.quit() 
        print('success')
    except smtplib.SMTPException as e:
        print('error',e) #打印错误
    return "success"

if __name__ == '__main__':
    app.debug = False
    app.run(host='0.0.0.0', port=5000)
    
    client = mqtt.Client("webServer")
    client.username_pw_set("iot_test", "bilibili")
    client.connect('140.143.18.81', 1883, 5)
    client.subscribe('TemperatureTopic', qos=0)
    client.on_message = on_message_come
    client.loop_forever()